package org.zsk.cs.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zsk.fastdev.stream.ForEachUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *     下载文件 controller
 * </p>
 *
 * @author zsk
 * @version 1.0
 * Created on 2020/5/17
 */
@RestController
@RequestMapping("/download")
@Slf4j
public class DownloadController {

    @GetMapping("registerResidentExcel")
    public void registerResidentExcel(HttpServletResponse response) throws IOException {
        //excel表头
        List<String> headers= Arrays.asList( "用户名", "密码");

        // Creating Workbook instances
        Workbook wb = new HSSFWorkbook();
        String fileName="批量注册居民信息表.xlsx";
        // An output stream accepts output bytes and sends them to sink.
        OutputStream fileOut = new FileOutputStream(fileName);
        // Creating Sheets using sheet object
        Sheet sheet1 = wb.createSheet("sheet1");
        //在excel表中添加表头
        Row row = sheet1.createRow(0);
        ForEachUtils.forEach(0,headers,(index, item)->{
            Cell cell = row.createCell(index);
            RichTextString text = new HSSFRichTextString(item);
            cell.setCellValue(text);
        });

        log.debug("批量注册居民信息表样板成功");

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        wb.write(response.getOutputStream());
    }


}
